package com.pvj.myaccount.ui.gallery

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.haibin.calendarview.Calendar
import com.haibin.calendarview.CalendarView
import com.haibin.calendarview.CalendarView.OnCalendarSelectListener
import com.pvj.myaccount.R
import com.pvj.myaccount.adapter.RecyclerViewAdapter
import com.pvj.myaccount.adapter.TodayAdapter
import com.pvj.myaccount.databinding.FragmentGalleryBinding
import com.pvj.myaccount.room.entity.Cost
import com.pvj.myaccount.ui.home.RecycleViewDivider
import com.pvj.myaccount.uitls.TimeUtil

class GalleryFragment : Fragment(), OnCalendarSelectListener, CalendarView.OnMonthChangeListener {
    private val mTAG = "GalleryFragment"
    private var _binding: FragmentGalleryBinding? = null

    private lateinit var galleryViewModel: GalleryViewModel

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private lateinit var recyclerViewAdapter: RecyclerViewAdapter

    private val mDayCostMap = HashMap<Int, TotalDayCost>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        galleryViewModel =
            ViewModelProvider(this)[GalleryViewModel::class.java]

        _binding = FragmentGalleryBinding.inflate(inflater, container, false)
        val root: View = binding.root

        this.context?.let { recyclerViewAdapter = RecyclerViewAdapter() }
        _binding!!.recyclerView.layoutManager = LinearLayoutManager(activity) // 用于线性布局
        _binding!!.recyclerView.adapter = recyclerViewAdapter
        //添加自定义分割线：可自定义分割线高度和颜色
        _binding!!.recyclerView.addItemDecoration(
            RecycleViewDivider(
                activity,
                LinearLayoutManager.HORIZONTAL,
                20,
                resources.getColor(R.color.app_bg)
            )
        )
        // initData()

        binding.tvMonthDay.text =
            "%d月%d日".format(binding.calendarView.curMonth, binding.calendarView.curDay)
        binding.tvLunar.text = "今日"
        binding.tvCurrentDay.text = binding.calendarView.curDay.toString()
        binding.calendarView.setOnCalendarSelectListener(this)
        binding.calendarView.setOnMonthChangeListener(this)

        galleryViewModel.monthList.observe(viewLifecycleOwner) {
            // 更新UI
            updateUI(it)
        }

        return root
    }

    override fun onResume() {
        super.onResume()
        refreshData()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onCalendarOutOfRange(calendar: Calendar?) {
    }

    override fun onCalendarSelect(calendar: Calendar, isClick: Boolean) {
        binding.tvLunar.visibility = View.VISIBLE
        binding.tvYear.visibility = View.VISIBLE
        binding.tvMonthDay.text =
            "%d月%d日".format(calendar.month, calendar.day)
        binding.tvYear.text = calendar.year.toString()
        binding.tvLunar.text = calendar.lunar

        Log.d(
            mTAG,
            "onCalendarSelect year:${calendar.year} month:${calendar.month} day:${calendar.day} isClick:${isClick}"
        )
        if (isClick) {
            recyclerViewAdapter.submitList(mDayCostMap[calendar.day]?.list)
        }
    }

    private fun refreshData() {
        val year: Int = binding.calendarView.curYear
        val month: Int = binding.calendarView.curMonth
        galleryViewModel.loadMonthData(year, month)
    }

    private fun getSchemeCalendar(
        year: Int,
        month: Int,
        day: Int,
        color: Int,
        text: String
    ): Calendar {
        val calendar = Calendar()
        calendar.year = year
        calendar.month = month
        calendar.day = day
        calendar.schemeColor = color //如果单独标记颜色、则会使用这个颜色
        calendar.scheme = text
        return calendar
    }

    override fun onMonthChange(year: Int, month: Int) {
        Log.d(mTAG, "onMonthChange ${year}:${month}")
        galleryViewModel.loadMonthData(year, month)
    }


    private fun updateUI(data: List<Cost>?) {
        // 更新列表、文本视图或其他UI组件
        Log.d(mTAG, "updateUI data= " + data.toString());
        val year: Int = binding.calendarView.selectedCalendar.year
        val month: Int = binding.calendarView.selectedCalendar.month
        val day: Int = binding.calendarView.selectedCalendar.day

        val map: MutableMap<String, Calendar> = HashMap()
        Log.d(mTAG, "updateUI year:${year} month:${month} day:${day}");
        mDayCostMap.clear()
        if (data != null) {
            for (cost in data) {
                val costDay = TimeUtil.timestampToBeijingDay(cost.eventTime)
                Log.d(mTAG, "eventTime:${cost.eventTime} day:${costDay}")
                var totalDayCost = mDayCostMap[costDay]
                if (totalDayCost == null) {
                    totalDayCost = TotalDayCost()
                }
                totalDayCost.total += cost.money
                totalDayCost.list.add(cost)
                mDayCostMap[costDay] = totalDayCost
                map[getSchemeCalendar(year, month, costDay, -0xbf24db, "").toString()] =
                    getSchemeCalendar(
                        year,
                        month,
                        costDay,
                        -0xbf24db,
                        totalDayCost.total.toString()
                    )
            }
            recyclerViewAdapter.submitList(mDayCostMap[day]?.list)
            //此方法在巨大的数据量上不影响遍历性能，推荐使用
            binding.calendarView.setSchemeDate(map)
        }

    }

}